﻿$G.money = {
	defaults: {
		decimal_separator: ',',
		thousands_separator: '.',
		currency_symbol: '€',
		decimals: 2
	},

	toMoney: function (number, options) {
		var o = typeof options === 'undefined' ? this.defaults : options;
		var n = number,
		c = isNaN(o.decimals) ? this.defaults.decimals : Math.abs(o.decimals),
		d = o.decimal_separator || this.defaults.decimal_separator,
		t = (typeof o.thousands_separator === 'undefined') ? this.defaults.thousands_separator : o.thousands_separator, //if you don't want to use a thousands separator you can pass empty string as thousands_sep value
		sign = (n < 0) ? '-' : '',
		//extracting the absolute value of the integer part of the number and converting to string
		i = parseInt(n = Math.abs(n).toFixed(c)) + '',
		j = ((j = i.length) > 3) ? j % 3 : 0;
		return o.currency_symbol + ' ' + sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
	},

	toCents: function (str, options) {
		var o = typeof options === 'undefined' ? this.defaults : options;

		var a = str.trim();
		var neg = false;
		var first;
		var points = 0;
		var cents = 0;

		if (a.length == 0)
			return undefined;

		if (first == o.currency_symbol)
			a = a.substr(1).trim();

		first = a.charAt(0);

		if (first == '-')
			neg = true;

		if (first == '-' || first == '+')
			a = a.substr(1).trim();

		var fractions = 0;
		for (var i = 0; i < a.length; i++) {
			var c = a.charAt(i);
			if (c == o.thousands_separator) continue;
			if (c == o.decimal_separator) {
				points++;
				if (points > 1) //too many decimal points
					return undefined;
			}
			else {
				if (isNaN(c)) //illegal char
					return undefined;

				if (points == 1) {
					fractions++;
					if (fractions > 2) //too many decimals
						return undefined;
				}
				cents = cents * 10 + Number(c);
			}
		}

		if (points == 0 || fractions == 0)
			cents *= 100;
		else if (fractions == 1)
			cents *= 10;

		if (neg)
			cents = -cents;

		return cents;
	}
}